﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MessageCallAspect.Aspect.Cache
{
    public class MemoryCacheProvider : ICacheProvider
    {
        private readonly Dictionary<object, CacheObject> m_Dic = new Dictionary<object, CacheObject>();
        private readonly object syncRoot = new object();

        public MemoryCacheProvider()
        {

        }
        #region ICacheModule Members

        public object Get(object uid, TimeSpan? timeout)
        {
            lock (syncRoot)
            {
                if (!m_Dic.ContainsKey(uid))
                    return null;

                CacheObject obj = m_Dic[uid];
                if (timeout.HasValue && obj.IsExpired(timeout.Value))
                {
                    m_Dic.Remove(uid);
                    return null;
                }
                else
                {
                    return obj.Value;
                }
            }
        }

        public void Set(object uid, object value)
        {
            lock (syncRoot)
            {
                m_Dic[uid] = new CacheObject(DateTime.Now, value);
            }
        }

        #endregion
    }
}
